var util = require('../../../utils/util.js');
var app = getApp();
Page({
   data: {
      ding: "",
      sessionid: '',
      runDataYesterday: '',
      runData: [],
      userInfo: {},
      dingtotal: '',
      animationData: {},
      shenhedisplay: 'block',
      condisplay: 'none',
      level1disabled: 'gray',
      level2disabled: 'gray',
      level3disabled: 'gray',
      level1text: '正在登录...',
      level2text: '级别不够',
      level3text: '级别不够',
      con1bg: "",
      con2bg: "",
      con3bg: "",
      level1display: "none",
      level2display: "none",
      level3display: "none",
      musiclist: [],
   },
   onLoad: function () {
      wx.showShareMenu({
         withShareTicket: true
      })
   },
   onShow: function () {
      util.showMsg('正在登录...');
      /*var animation = wx.createAnimation({
         duration: 10000,
         timingFunction: 'ease',
      })
      this.animation = animation
   */
      this.setData({
         //animationData: animation.export()
         level1display: "none",
      })

      var that = this;
      //var sessionid = wx.getStorageSync('sessionid');
      //var userInfo = wx.getStorageSync('userInfo');
      //console.log('loadingonShow');
      wx.clearStorage();
      wx.clearStorageSync();
      that.getUserInfo();
      /* if (!sessionid) {
       } else {
          that.setData({
             sessionid: sessionid,
             userInfo: userInfo
          });
                console.log('loadOnload');
          //that.getIndexData(projectid);
       }*/
   },
   getUserInfo: function (cb) {
      var that = this;
      //var sessionid = wx.getStorageSync('sessionid');
      //调用登录接口
      wx.login({
         success: function (r) {
            var sysinfo = wx.getSystemInfoSync();
            //console.log(sysinfo);
            wx.getUserInfo({
               success: function (res) {
                  wx.getNetworkType({
                     success: function (resnet) {
                        // 返回网络类型, 有效值：
                        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
                        var networkType = resnet.networkType;
                        that.login({
                           model: sysinfo.model,
                           language: sysinfo.language,
                           version: sysinfo.version,
                           system: sysinfo.system,
                           platform: sysinfo.platform,
                           SDKVersion: sysinfo.SDKVersion,
                           screenWidth: sysinfo.screenWidth,
                           screenHeight: sysinfo.screenHeight,
                           networkType: networkType,
                           code: r.code,
                           iv: res.iv,
                           encryptedData: encodeURIComponent(res.encryptedData),
                           _: (new Date()).getTime() 　//加个随机参数
                        })
                     }
                  })
                  typeof cb == "function" && cb(that.globalData.userInfo)
               },
               fail: function (emsg) {
                  util.showMsg('由于您刚才选择了拒绝授权，只能等待一段时间重试，或者你卸载小程序重新添加!');
               }
            })
         }
      })
   },
   login: function (param) {
      var that = this;
      wx.request({
         url: app.globalData.url + 'Xcc/login',
         data: param,
         method: 'POST',
         header: app.globalData.header,
         //header: { 'content-type': 'application/json' },
         success: function (res) {
            //console.log(res);
            if (res.data == null || '' == res.data) {
               //console.log(res);
               wx.clearStorage();
               //util.showMod('请联系管理员授权微信账号!');
            } else {
               wx.setStorageSync('sessionid', res.data.sessionid);
               wx.setStorageSync('userInfo', res.data);
               //wx.setStorageSync('header', { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'PHPSESSID=' + res.data.sessionid });
               //that.globalData.header = { 'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'PHPSESSID=' + res.data.sessionid };
               console.log('登录数据存储成功！');
               util.showMsg('正在获取运动记录...');
               if (!wx.getWeRunData) {
                  util.showMsg('您的微信获取不到运动数据');
               } else {
                  wx.getWeRunData({
                     success(resrun) {
                        const encryptedData = resrun.encryptedData
                        resrun['sessionid'] = res.data.sessionid;
                        //console.log(res);
                        wx.request({
                           url: app.globalData.url + 'Ydrundata/runData',
                           data: resrun,
                           method: "POST",
                           header: app.globalData.header,
                           fail: function (resRun) {
                              wx.stopPullDownRefresh() //停止下拉刷新
                              util.showMsg('获取数据失败' + resRun);
                           },
                           success: function (resRun) {
                              //wx.hideNavigationBarLoading() //完成停止加载
                              wx.stopPullDownRefresh() //停止下拉刷新
                              //console.log(res);
                              if (resRun.data.status == 0) {
                                 //util.showMod(res.data.info);
                                 that.setData({
                                    level1text: '请授权再使用',
                                    userInfo: res.data,
                                    runData: resRun.data.data,
                                    //con1bg: res.data.loadingbg['con1bg'],
                                    //con2bg: res.data.loadingbg['con2bg'],
                                    //con3bg: res.data.loadingbg['con3bg'],
                                 });
                              } else {
                                 //console.log(resRun);
                                 wx.setStorageSync('runDataYesterday', resRun.data.data[1]['step']);
                                 wx.setStorageSync('dingtotal', resRun.data.dingtotal);
                                 wx.setStorageSync('rundatapeizhi', resRun.data.rundatapeizhi);
                                 wx.setStorageSync('piaofutext', resRun.data.piaofutext);
                                 wx.setStorageSync('getdingFlag', resRun.data.getdingFlag);
                                 that.setData({
                                    ding: "https://weixin.xajlnkyjy.com/tp323/Jishu/Yundong/Images/ding.gif",
                                    dingtotal: resRun.data.dingtotal,
                                    level1disabled: '',
                                    level1text: '点击进入',
                                    runDataYesterday: resRun.data.data[1]['step'],
                                    con1bg: resRun.data.loadingbg['con1bg'],
                                    con2bg: resRun.data.loadingbg['con2bg'],
                                    con3bg: resRun.data.loadingbg['con3bg'],
                                    shenhedisplay: 'none',
                                    condisplay: 'block',
                                    level1display: "",
                                    level2display: "",
                                    level3display: "",
                                    musiclist: resRun.data.musiclist,
                                 });

                                 if (resRun.data.dingtotal >= resRun.data.rundatapeizhi['level1total']) {
                                    that.setData({
                                       level2disabled: '',
                                       level2text: '点击开始',
                                    });
                                 }
                                 wx.hideToast();
                              }
                           }
                        })
                     },
                     fail: function (res) {
                        wx.hideToast();
                        console.log(res);
                        util.showMsg('获取运动数据失败' + res);
                     }
                  })
               }
            }
         },
         fail: function (err) {
            wx.hideToast();
            util.showMsg('登录失败!' + JSON.stringify(err));
         }
      })
   },
   gotoLevel1: function () {
      if (this.data.level1text == '正在登录...' || this.data.level1text == '请授权再使用') {
         util.showMsg('请先登录，如果登录失败请返回重试！');
      } else {
         // console.log(Object.keys(this.data.musiclist).length);
         var musicrand = util.getRand(1, Object.keys(this.data.musiclist).length);
         const backgroundAudioManager = wx.getBackgroundAudioManager();
         backgroundAudioManager.title = this.data.musiclist[musicrand].title;
         /*backgroundAudioManager.epname = '此时此刻'
         backgroundAudioManager.singer = '汪峰'*/
         backgroundAudioManager.coverImgUrl = this.data.musiclist[musicrand].coverImgUrl;
         backgroundAudioManager.src = this.data.musiclist[musicrand].src; // 设置了 src 之后会自动播放
         wx.navigateTo({
            url: '../index/index?id=1'
         })
      }
   },
   gotoLevel2: function () {
      var that = this;
      var rundatapeizhi = wx.getStorageSync('rundatapeizhi');
      if (this.data.dingtotal >= rundatapeizhi['level1total']) {
         that.setData({
            level2disabled: '',
            level2text: '点击开始',
         });
         wx.navigateTo({
            url: '../level2/level2?id=1'
         })
      } else {
         util.showMsg('级别不够！！');
      }

   },
   gotoLevel3: function () {
      var that = this;
      var rundatapeizhi = wx.getStorageSync('rundatapeizhi');
      if (this.data.dingtotal >= rundatapeizhi['level2total']) {
         that.setData({
            level2disabled: '',
            level2text: '点击开始',
         });
         /*wx.navigateTo({
                 url: '../index/index?id=1'
              })*/
      } else {
         util.showMsg('级别不够！！');
      }
   }
})